package org.millioncall.yueyoga.admin.action;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.millioncall.openplatform.util.StringUtils;
import org.millioncall.openplatform.util.WebAppUtils;
import org.millioncall.yueyoga.admin.model.ClassScheduleModel;
import org.millioncall.yueyoga.admin.model.Reservation;
import org.millioncall.yueyoga.admin.service.CheduleService;
import org.millioncall.yueyoga.admin.service.ReservationService;
import org.millioncall.yueyoga.admin.service.WeiXinService;
import org.millioncall.yueyoga.common.GlobalService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class WeiXinAction {
	private static final Logger LOGGER = LoggerFactory
			.getLogger(WeiXinAction.class);
	private WeiXinService weiXinService;
	private CheduleService cheduleService;
	private ReservationService reservationService;
	public WeiXinService getWeiXinService() {
		return weiXinService;
	}
	public void setWeiXinService(WeiXinService weiXinService) {
		this.weiXinService = weiXinService;
	}
	public CheduleService getCheduleService() {
		return cheduleService;
	}
	public void setCheduleService(CheduleService cheduleService) {
		this.cheduleService = cheduleService;
	}
	public ReservationService getReservationService() {
		return reservationService;
	}
	public void setReservationService(ReservationService reservationService) {
		this.reservationService = reservationService;
	}
	
	/**
	 * 添加注释
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "/front", method = RequestMethod.GET)
	public void check(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		// 微信加密签名
		String signature = request.getParameter("signature");
		// 时间戳
		String timestamp = request.getParameter("timestamp");
		// 随机数
		String nonce = request.getParameter("nonce");
		// 随机字符串
		String echostr = request.getParameter("echostr");

		PrintWriter out = response.getWriter();
		// 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
		if (weiXinService.check(signature, timestamp, nonce)) {
			out.print(echostr);
		}
		out.close();
	}

	/**
	 * 添加注释
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/front", method = RequestMethod.POST)
	public void postWeiBo(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String responseXml = "";
		// 1.获取到请求的消息xml
		String xmlData = getWeixinRequestXML(request);
		// 2.得到自动回复的消息xml
		Document doc = null;
		try {
			doc = DocumentHelper.parseText(xmlData);
		} catch (DocumentException e) {
			LOGGER.error("解析xml字符串时异常", e);
			responseXml = buildErrorMsgXML("消息", "系统异常，请稍后再试，或联系开发者!");
		}
		Element rootElt = doc.getRootElement();
		List<Element> list = rootElt.elements();
		Map<String, String> params = new HashMap<String, String>();
		for (Element e : list) {
			params.put(e.getName(), e.getText());
		}
		String path = request.getContextPath();
		String basePath = request.getScheme() + "://" + request.getServerName()
				+ ":" + request.getServerPort() + path + "/";
		params.put("basePath", basePath);// 项目基路径
		
		String msgType = params.get("MsgType");
		if ("event".equals(msgType)) {
			responseXml = weiXinService.handleEventMsg(params);
		} else if("text".equals(msgType)){
			responseXml = weiXinService.handleTextMsg(params);
		}

		// 3.把回复xml写给微信服务器
		if (StringUtils.isEmpty(responseXml)) {
			responseXml = "";//
		} else {
			response.setCharacterEncoding("utf-8");
			PrintWriter writer = response.getWriter();
			writer.write(responseXml);
			writer.flush();
			writer.close();
		}
	}

	/**
	 * 根据异常信息生成一个响应的异常xml格式字符串
	 * 
	 * @param type
	 *            类型
	 * @param msg
	 *            消息内容
	 * @return
	 */
	private String buildErrorMsgXML(String type, String msg) {
		return "";
	}

	/**
	 * 
	 * @param request
	 * @return
	 */
	private String getWeixinRequestXML(HttpServletRequest request) {
		InputStream is = null;
		try {
			is = request.getInputStream();
		} catch (IOException e) {
			LOGGER.error("获取微信请求的xml时IO异常", e);
			return buildErrorMsgXML("消息", "系统异常，请稍后再试，或联系开发者!");// 出错的异常提示xml
		}
		int size = request.getContentLength();
		byte[] buffer = new byte[size];
		byte[] xmldataByte = new byte[size];
		int count = 0;
		int rbyte = 0;
		while (count < size) {
			try {
				rbyte = is.read(buffer);
			} catch (IOException e) {
				LOGGER.error("读取xml字符串时异常", e);
				return buildErrorMsgXML("消息", "系统异常，请稍后再试，或联系开发者!");// 出错的异常提示xml
			}
			for (int i = 0; i < rbyte; i++) {
				xmldataByte[count + i] = buffer[i];
			}
			count += rbyte;
		}
		try {
			is.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			return new String(xmldataByte, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			LOGGER.error("转码异常（不支持的编码转换）", e);
			return buildErrorMsgXML("消息", "系统异常，请稍后再试，或联系开发者!");// 出错的异常提示xml
		}
	}
	
	/** 根据日期获取课程信息 */
	@RequestMapping(value = "/scheduleListByDate.jhtml")
	public String ajaxGetTScheduleList(String clazzId, String type,
			String memberId, HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {
		GlobalService.initBasicData(request, model);
		model.put("memberId", memberId);
		model.put("clazzId", clazzId);
		String kcrq="";
		if (StringUtils.isNotBlank(type)) {
			Calendar cal = Calendar.getInstance();
			cal.setTime(new Date());
			cal.add(Calendar.DAY_OF_YEAR, 1);
			SimpleDateFormat time=new SimpleDateFormat("MM-dd");
			kcrq=time.format(cal.getTime());
			model.put("type", 1);
		}else{
			Date nowTime=new Date();
			SimpleDateFormat time=new SimpleDateFormat("MM-dd");
			kcrq=time.format(nowTime);
			model.put("type", 0);
		}
		List<ClassScheduleModel> csmList = cheduleService.findScheduleInfoList(clazzId, kcrq,null, memberId);
		for (ClassScheduleModel classScheduleModel : csmList) {
			if("接受预定".equals(classScheduleModel.getYdzt())){
				Reservation reservation = reservationService.findResvScheduleInfoByScheIdAndMemberId(classScheduleModel.getKcxh(),memberId);
				if(reservation!=null){
					classScheduleModel.setYdbh("true");
				}else{
					classScheduleModel.setYdbh("false");
				}	
			}
		}
		model.put("csmList", csmList);
		return "schedule_list";
	}
	
	/** 根据条件取消预定的课程 */
	@RequestMapping(value = "/ajaxCancelSchedule.jhtml")
	public void ajaxCancelSchedule(String scheduleId, String memberId,
			HttpServletRequest request, HttpServletResponse response,
			ModelMap model) {
		String json = "{'success':false, 'msg':'取消预约失败!'}";
		if (StringUtils.isBlank(scheduleId) || StringUtils.isBlank(memberId)) {
			WebAppUtils.ajaxResponse(response, json);
			return;
		}
		boolean flag = reservationService.cancelResvSchedule(scheduleId,
				memberId);
		if (flag) {
			json = "{'success':true, 'msg':'取消预约成功!'}";
		}
		WebAppUtils.ajaxResponse(response, json);
	}
	
	/** 根据条件预定课程 */
	@RequestMapping(value = "/ajaxResvSchedule.jhtml")
	public void ajaxResvSchedule(String scheId, String memberId,
			HttpServletRequest request, HttpServletResponse response,
			ModelMap model) {
		String json = "{'success':false, 'msg':'预定课程失败!'}";
		if (StringUtils.isBlank(scheId) || StringUtils.isBlank(memberId)) {
			WebAppUtils.ajaxResponse(response, json);
			return;
		}
		int rtv = reservationService.resvSchedule(scheId, memberId);
		String msg = "";
		boolean flag = false;
		if (rtv == 1) {
			msg = "预约成功!";
			flag = true;
		} else if (rtv > 1) {
			msg = "不能重复预约!";
		} else {
			msg = "预约失败!";
		}
		json = "{'success':" + flag + ", 'msg':'" + msg + "'}";
		WebAppUtils.ajaxResponse(response, json);
	}

}
